package com.fxnotes.book.utils;

import java.util.concurrent.TimeUnit;

public class EventListener implements Listener {

    private static final int SLEEP_TIME = 200;

    @Override
    public boolean waitFor(Event event, int timeout, TimeUnit timeUnit) {
        event.trigger();

        boolean condition = false;
        long waitTime = convertToMillis(timeout, timeUnit);
        while (waitTime > 0 && !(condition = event.checkCondition())) {
            sleep(SLEEP_TIME);
            waitTime -= SLEEP_TIME;
        }

        return condition;
    }

    private long convertToMillis(long timeout, TimeUnit timeUnit) {
        return TimeUnit.MILLISECONDS.convert(timeout, timeUnit);
    }

    private void sleep(int time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
        }
    }

    public static boolean waitForEvent(Event event, int timeout, TimeUnit timeUnit) {
        return new EventListener().waitFor(event, timeout, timeUnit);
    }
}
